<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class CustomerAddress extends Model
{
    use HasFactory;

    protected $table = 'customer_address';

    protected $primaryKey = 'id';

    public $timestamps = false;

    protected $fillable = [
        'customer_id',
        'name',
        'phone',
        'six',
        'pathid',
        'address',
        'status',
        'delete_flg',
        'create_at',
        'update_at',
    ];

    public function getList(array $params): array
    {
        $whereSql = self::conditions($params);

        $sql = "
            SELECT
                ca.id,
                ca.customer_id,
                ca.name,
                ca.phone,
                ca.pathid,
                ca.six,
                ca.address,
                ca.status,
                c.username as customer_name,
                ad.area_name as district_name,
                ad.pathid as district_pathid,
                ac.area_name as city_name,
                ac.pathid as city_pathid,
                ap.area_name as province_name,
                ap.pathid as province_pathid
            FROM
                `customer_address` ca
                LEFT JOIN customer c ON c.id = ca.customer_id
                LEFT JOIN area ad ON ad.pathid = ca.pathid
                LEFT JOIN area ac ON ac.id = ad.parent_id
                LEFT JOIN area ap ON ap.id = ac.parent_id
            WHERE
                ca.delete_flg = 0
                {$whereSql}
        ";
        return DB::select($sql);
    }

    public static function conditions(array $params): string
    {
        $whereSql = "";

        if (!empty($params['status'])) {
            $whereSql .= "and ca.status = '{$params['status']}'";
        }
        if (!empty($params['customer_id'])) {
            $whereSql .= "and ca.customer_id = '{$params['customer_id']}'";
        }

        return $whereSql;
    }
}
